import { defineStore } from 'pinia'
import { AppState } from './types'
import { settingsConfig } from '@/api/system/settings'
import { setPrimaryColor } from '@/libs/palette'

const useAppStore = defineStore('app', {
    state: () => ({
        sysName: undefined,
        logo: undefined,
        icon: undefined,
        loginBanner: undefined,
        iconType: undefined,
        primaryColor: undefined,
        enableWatermark: undefined,
        copyrightYear: undefined,
        copyrightName: undefined,
        copyrightLink: undefined,
        icp: undefined
    }),
    getters: {
        appSettings(state: AppState): AppState {
            return { ...state }
        }
    },
    actions: {
        async refreshAppSettings() {
            const { data } = await settingsConfig()
            this.$patch(data)

            // 设置页面标题
            document.title = data.sysName ? data.sysName : ''
            // 设置favicon
            if (data.icon) {
                const favicon = document.createElement('link')
                favicon.rel = 'icon'
                favicon.type = data.iconType ? data.iconType : 'image/x-icon'
                favicon.href = data.icon
                document.head.appendChild(favicon)
            }
            // 设置主色调
            if (data.primaryColor) {
                setPrimaryColor(data.primaryColor)
            }
        }
    }
})

export default useAppStore
